<?php
namespace Utuo;

use Utuo\DistributionShopForeground;
use My\Model\DistributionShopOrderModel;
use My\Model\WechatUserModel;
use Home\Logic\DistributionShopRedPacketLogic;
use My\Model\UserRole;
use My\Model\DeliveryModel;

class DistributionShopOrderController extends DistributionShopForeground {
	
	// 购物车
	protected $cart = null;
	
	
	/**
	 * 初始化
	 */
	public function _init() {
		layout ( 'disshop' );
		$this->setModelName ( "DistributionShop" );
		$this->setModelControllerName( "DisShop" );
		$this->cart = $this->getCart ();
		ACTION_NAME == "signIn" and \Think\Hook::add('disorder_completed', 'Home\\Behaviors\\DistributionShopOrderCompletedBehavior');
	}
	
	/**
	 * 我的订单
	 */
	public function listAction() {
		$type = I ( "type" );
		$m = M ( "DistributionShopOrder orders" );
		$condition = array (
			"orders.uid" => $this->uid,
		);
		
		if ($type == 1) { // 未付款
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_PAY;
		} else if ($type == 2) { // 待签收(已付款,货到付款)
			$condition ['orders.order_status'] = array (
					"in",
					array (
							DistributionShopOrderModel::ORDER_STATUS_SHIPPING,
							DistributionShopOrderModel::ORDER_STATUS_SIGN
					)
			);
			unset( $condition['orders.uid'] );
			/* 送礼订单 */
			$m->join ( "__DISTRIBUTION_SHOP_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" );
			$condition['orders.id'] = array('exp', "is not null and (
																((gifts.to_uid=0 or gifts.to_uid is null) and orders.uid={$this->uid}) 
																	or 
																(gifts.to_uid={$this->uid})
															) ");
		} else if ($type == 3) { // 交易成功
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
		}  else if ($type == 4) { // 退款订单
			$condition['orders.refund_times'] = array('gt', 0);
		} else { // 其它
			$condition ['orders.order_status'] = array (
					"not in",
					array (
							DistributionShopOrderModel::ORDER_STATUS_PAY,
							DistributionShopOrderModel::ORDER_STATUS_SHIPPING,
							DistributionShopOrderModel::ORDER_STATUS_SIGN,
							DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
					),
			);
		}
		$orderLists = $m->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
						->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
						->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
						->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
						->where ( $condition )->order("orders.id desc")->select ();
		$this->bindOrderDetail ( $orderLists );
		$this->assign("types", \My\Model\DistributionShopOrderModel::$TYPES);
		$this->assign ( "orderLists", $orderLists );
		$this->display ( "{$this->modelControllerName}/orderList" );
	}
	
	/**
	 * 订单结算页
	 */
	public function confirmOrderAction() {
		$orderId = I('orderId', 0, "intval");
		$order = array();
		if ( $orderId ) {
			$order = $this->getPayingOrder( $orderId );
		} else {
			$order = $this->getSaveingOrder();
		}
		session ( "order", $order );
		$redPacketsLists = DistributionShopRedPacketLogic::getRedPacketsUseable($this->uid, $order['goodsTotalPrice']);
		$this->assign ( "deliveryMethod", DeliveryModel::$METHOD);
		$this->assign ( "redPacketsLists", $redPacketsLists );
		$this->assign ( "orderJSON", json_encode ( $order ) );
		$this->assign ( 'order', $order );
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->display ( "{$this->modelControllerName}/" . ACTION_NAME );
	}
	
	/**
	 * 获得已保存欲支付订单
	 * @return array 格式参考getSaveingOrder
	 */
	protected function getPayingOrder( $id ) {
		$addressId = I('addressId', 0, "intval");
		$order = $this->getOrder($id);
		if ( $order ) {
		    $d = D ( "My/DistributionShopGoods", "Model" );
		    $totalShpping = array();
			/* 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口) */
			$produtPayApiLists = $this->getPayApiList();
			if ( $order['support_cod']*1 ) {
				$produtPayApiLists = array_merge($produtPayApiLists, array('COD' =>"货到付款"));
			}
			/* 转化为确认订单可显示的格式 */
			$order['createTime'] = $order['create_time'];
			$order['orderNo'] = $order['order_id'];
			$order['totalPrice'] = number_format($order['actual_cost'], 2);
			$order['goodsTotalPrice'] = $order['goods_amount'];
			$order['shippingTotalPrice'] = $order['shipping_fee'];
			$order['rewardCurrency'] = $order['reward_currency'];
			$order['currencyValue'] =  $order['currency_value'];
			$order['redPacketOffset'] = $order['red_packet_offset'];
			$order['shippingId'] = $order['shipping_id'];
			$order['productPayApiOptions'] =  $this->getOption( $produtPayApiLists );	
			/* 收货地址 */
			if ( $addressId ) {
				$address = $this->getAddress($addressId);
			} else {
				$address = array(
					'name' => $order['consignee'],
					'province' => $order['province'],
					'city' => $order['city'],
					'area' => $order['area'],
					'address' => $order['address'],
					'tel' => $order['tel'],
					'provinceName' => $order['provinceName'],
					'cityName' => $order['cityName'],
					'areaName' => $order['areaName'],
				);
			}
			$order['address'] = $address;	
			/* 订单之前选择的红包 */
			if ( $order['red_packet_id'] ) {
				$packet = M("DistributionShopRedPacket")->where(array('id'=>$order['red_packet_id']))->field('id,code,value')->find();
				$order['redPacketId'] = $order['red_packet_id'];
				$order['redPacketCode'] = $packet['code'];
				$order['redPacketValue'] = $packet['value'];
				$order['redPacketOffset'] = $order['red_packet_offset'];
			}
			foreach ( $order['orderItems'] as $productId => &$productItems ) {
				$productItems['name'] = $productItems['productName'];
				foreach ( $productItems['items'] as $businessId => &$items) {
				    $goodsSnap = $items['goodsSnap'];
					$items['quantity'] = $items['productNumber'];
					$items['attrs'] = $items['productAttr'];
					$items['pic'] = $items['productPic'];
					/* 计算运费 */
					$shippingPrice = $d->getShipping ( $productId, $items['productNumber'], $goodsSnap['shipping_tpl_id'], $address['province'], $goodsSnap );
				    foreach ( $shippingPrice as $k => $v1 ) {
				        $totalShpping[$k] += $v1;
				    }
					unset($items['productNumber']);
					unset($items['productAttr']);
					unset($items['productPic']);
					unset($items['rate_status']);
				}
				unset($productItems['productName']);
			}
			
			/* 总运费数组 */
			$order["shippingTotalPrice"] = 0;
			if ( $totalShpping ) {
			    $order['totalShippingArray'] = $totalShpping;
			    if ( !$order['shippingId'] ) {
			        $order['shippingId'] = 1;
			    }
			    $order["shippingTotalPrice"] = $totalShpping[$order['shippingId']];
			}
			
			$order['totalPrice'] = $order['goodsTotalPrice'] - $order['redPacketOffset'] + $order["shippingTotalPrice"];
			
			foreach ( explode(',', "create_time,order_id,goods_amount,shipping_fee,consignee,province,city,area,tel") as $v ) {
			    unset($order[$v]);
			}
			return $order;
		}
	}
	
	/**
	 * 获得欲保存订单
	 * @return
	 * array(
	 *  ["atOnce"] => int(1)
	 *  ["createTime"] => int(1417767435)
	 *  ["orderNo"] => string(22) "1412051617150000011771"
	 *  ["totalPrice"] => float(138)
	 *  ["goodsTotalPrice"] => float(138)
	 *  ["shippingTotalPrice"] => float(0)
	 *  ["productPayApiOptions"] => string(46) "<option value='WxTenpay'>微信支付</option>"
	 *  ["orderItems"] => array(1) {
	 *  ["8"] => &array(4) {
	 *    ["productId"] => string(1) "8"
	 *    ["name"] => string(26) "阿芙薰衣草精油10ml "
	 *    ["support_cod"] => string(1) "0"
	 *    ["items"] => array(1) {
	 *      ["b123198bb0678beddc453e07c57bbc48c8141776743580"] => &array(5) {
	 *        ["businessId"] => string(46) "b123198bb0678beddc453e07c57bbc48c8141776743580"
	 *        ["productPrice"] => string(6) "138.00"
	 *        ["quantity"] => int(1)
	 *        ["attrs"] => NULL
	 *        ["pic"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-11-14/2014111411424640164318.jpg"
	 *      }
	 *    }
	 *  }
	 * }
	 * ["supportCod"] => int(0)
	 * ["address"] => array(13) {
	 *   ["id"] => string(1) "1"
	 *   ["uid"] => string(2) "29"
	 *   ["name"] => string(6) "宋义"
	 *   ["province"] => string(6) "230000"
	 *   ["city"] => string(6) "230200"
	 *   ["area"] => string(6) "230204"
	 *   ["zipcode"] => string(0) ""
	 *   ["address"] => string(15) "ewqrewqrewqrewq"
	 *   ["tel"] => string(11) "13849089206"
	 *   ["status"] => string(1) "1"
	 *   ["provinceName"] => string(12) "黑龙江省"
	 *   ["cityName"] => string(15) "齐齐哈尔市"
	 *   ["areaName"] => string(9) "铁锋区"
	 * }
	 * )
	 */
	protected function getSaveingOrder() {
		$d = D ( "My/DistributionShopGoods", "Model" );
		$items = $this->getItems(); // 获得要结算的商品
		$totalPrice = 0; // 总价
		$supportCod = 1; // 默认支持货到付款
		$totalShpping = '';
		$address = $this->getAddress();
		$rewardCurrency = 0; // 最大返积分
		$currencyValue = 0; // 最大用积分
		foreach ( $items ["items"] as &$v ) {
			$count = 0; // 购买数量
			$subtotal = 0; // 小计
			/* 判断订单中每件商品是否支持货到付款，从而求出整个订单是否支持货到付款  */
			$goodsSnap = null;
			if ( !$v['support_cod']*1 ) $supportCod = 0;
			/* 处理显示属性可看 */
			foreach ( $v ['items'] as &$v0 ) {
			    $goodsSnap = $v0['goodsSnap'];
				$count += $v0 ['quantity'];
				$subtotal += $v0 ['productPrice'] * $v0 ['quantity'];
				/* 商城币  */
				$rewardCurrency += $v0['rewardCurrency'] * $v0 ['quantity'];
				$currencyValue += ceil($v0['currencyValue'] * ($goodsSnap['currency_percent']/100) * $v0 ['quantity']);
			}
			/* 计算运费 */
			$shippingPrice = $d->getShipping ( $v['productId'], $count, $goodsSnap['shipping_tpl_id'], $address['province'], $goodsSnap );
			if ( is_array($shippingPrice) ) {
				foreach ( $shippingPrice as $k => $v1 ) {
					$totalShpping[$k] += $v1;
				}
			} else {
				$totalShpping += $shippingPrice;
			}
			$totalPrice += $subtotal;
		}
		
		// 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口)
		$produtPayApiLists = $this->getPayApiList();
		if ( $supportCod ) {
			$produtPayApiLists = array_merge($produtPayApiLists, array('COD' =>"货到付款"));
		}
		$order = array (
			'atOnce' => $items ["atOnce"],
			'createTime' => time (),
			'orderNo' => date ( "ymdHis" ) . str_pad ( $this->sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 ), // 订单号
			'totalPrice' => $totalPrice + (is_array($totalShpping) ? current($totalShpping)*1 : $totalShpping*1),
			'goodsTotalPrice' => $totalPrice,
			'shippingTotalPrice' => (is_array($totalShpping) ? current($totalShpping)*1 : $totalShpping*1), // 配送方式数据(确认订单,更改地址时使用)
			'productPayApiOptions' => $this->getOption( $produtPayApiLists ),
			'orderItems' => $items ["items"],
			'supportCod' => $supportCod,
		    'rewardCurrency' => $rewardCurrency,
		    'currencyValue' => $currencyValue,
		);
		
		is_array($totalShpping) and $order['totalShippingArray'] = $totalShpping;
 		
		/* 获得用户默认收货地址 */
		$order ['address'] = $address;
		
		/* 附加数据 */
		method_exists($this, '_after_get_saving_order') and $this->_after_get_saving_order( $order );
		return $order;
	}
	
	/**
	 * 确认支付订单
	 */
	public function confirmOrderPostAction() {
		$orderId = I('orderId', 0, "intval"); // 订单id
		$orderNo = I ( 'orderNo', 0 ); // 订单单号
		$payApitype = I("apitype", ""); // 支付方式
		$buyMethod = I("buyMethod", 0, "intval"); // 购买方式
		$shippingId = I("shipping_id", 0, "intval"); // 配送方式id
		$sessionOrder = session ( "order" ); // 要保存或已保存的订单
		
		if ( $this->config['buy_required_subscribe'] ) {
		    $this->user['subscribe'] or $this->error("未关注不能下单");
		}
		
		if ( !$orderId ) {
			$orderId = $this->addOrder($orderNo, $payApitype);
		} else {
			$order = M("DistributionShopOrder")->where('id=%d', $orderId)->find();
			$orderGoodsList = M( "DistributionShopOrderGoods a" )->join("__DISTRIBUTION_SHOP_GOODS__ b on a.product_id=b.id", "LEFT")->where ( "a.order_id=%d", $orderId )->field("b.*")->select ();
			foreach ($orderGoodsList as $v) {
			    if ( $v['deleted']) {
			        $this->error('商品已不存在');
			    } elseif ( !$v['status'] ) {
			        $this->error("商品已下架");
			    }
			}
			$oldActualCost = $order['actual_cost'];
			/** 更新订单 */
			$modifyData = array();
			$addressId = I('addressId', 0, "intval");
			/* 更新订单收货地址 */
			$addressId and $address = $this->getAddress($addressId, 0);
			if ( $address ) {
				$modifyData = array_merge($modifyData, array(
					'consignee' => $address ['name'],
					'province' => $address ['province'],
					'city' => $address ['city'],
					'area' => $address ['area'],
					'address' => $address ['address'],
					'zipcode' => $address ['zipcode'],
				));
			}
			
			/* 配送费 */
			$shippingTotalPrice = $order ['shipping_fee']*1; // 配送总运费
			if ( isset($_REQUEST['shipping_id']) and isset($sessionOrder['totalShippingArray']) ) {
			    $shippingTotalPrice = $sessionOrder ['totalShippingArray'][$shippingId]*1;
			}
			/* 配送方式 */
			if ( isset($_REQUEST['shipping_id']) and $shippingId != $order['shipping_id'] ) {
			    $modifyData['shipping_id'] = $shippingId;
			}
			/* 配送价格改变 */
			if ( $shippingTotalPrice != $order ['shipping_fee']*1 ) { // 配送金额发生改变
			    $modifyData['shipping_fee'] = $shippingTotalPrice;
			}
			
    		/* 用户使用积分 */
    		$tmpCurrencyOffset = 0; // 使用积分
    		$tmpCurrencyRmb = 0; // 抵现
    		if ( $order['currency_value'] ) { // 支持使用积分
    		    $currencyOffset = I("currency_offset", 0, "intval") and $currencyOffset < 0 and $currencyOffset = 0;
    		    ($currencyOffset > $order['currency_value']) and $this->error("输入的积分不得大于{$order['currency_value']}");
    		    if ( $currencyOffset ) {
    		        $success = $this->checkCurrency($currencyOffset) or $this->error("可用积分不足");
    		    }
    		    $tmpCurrencyOffset = $currencyOffset*1;
    		    $tmpCurrencyRmb = sprintf("%.2f", $tmpCurrencyOffset*$this->config['currency_config']['value']/100); 
    		}
    		
    		/* 计算实际返积分 */
    		$tmpActualRewardCurrency = 0;
    		if ( $order['reward_currency'] ) {
    		    if ( $tmpCurrencyOffset*1 ) {
    		       $actualRewardCurrency = $order['reward_currency'] - ceil($tmpCurrencyOffset/10)*1; // 每用10积分少返1积分
    		       $tmpActualRewardCurrency = $actualRewardCurrency = $actualRewardCurrency > 0 ? $actualRewardCurrency : 0;
    		    } else {
    		       $tmpActualRewardCurrency = $order['reward_currency'];
    		    }
    		}
    		
    		/* 临时数据支付成功后成立 */
    		$modifyData['currency_tmp'] = serialize(array(
        		    'currency_offset' => $tmpCurrencyOffset,
        		    'currency_rmb' => $tmpCurrencyRmb,
        		    'actual_reward_currency' => $tmpActualRewardCurrency,
    		));
			
			/* 更新选择使用的红包 */
			$packetCode = I('packetCode', '');
			$redPacket = M("DistributionShopRedPacket")->where(array('uid'=>$this->uid, 'code'=>$packetCode, 'efficacy'=>1))->find();
			if ( $redPacket ) {
				if ( $redPacket != $order['red_packet_id'] ) {
					$modifyData['red_packet_id'] = $redPacket['id'];
					$modifyData['red_packet_offset'] = $redPacket['value'] >= $order['goods_amount'] ? $order['goods_amount'] : $redPacket['value'];
				}
			} else {
				if ( $order['red_packet_id'] ) {
					$modifyData['red_packet_id'] = 0;
					$modifyData['red_packet_offset'] = 0;
				}
			}
			
			$modifyData['actual_cost'] = $shippingTotalPrice + $order["goods_amount"] - $modifyData['red_packet_offset'] - $modifyData['currency_rmb'];
			
			/* 订单金额变更 */
			if ( $modifyData['actual_cost'] != $oldActualCost ) {
			    $modifyData['order_id'] = DistributionShopOrderModel::randOrderNo($this->sid); // 订单号
			}
			
			/* 绑定订单代理分成 */
			$modifyAgentReward = $this->bindOrderAgentReward( $order );
			$modifyAgentReward and $modifyData = array_merge($modifyData, $modifyAgentReward);
			
			M("DistributionShopOrder")->where(array('uid'=>$this->uid, 'id'=>$orderId))->save($modifyData);
		}

		/* 购买方式下的订单处理 */
		if ( $buyMethod == DistributionShopOrderModel::BUY_METHOD_COQUETRY ) { // 找人代付订单
			redirect(U("DisShopCoquetryOrder/payAnother", "id={$orderId}&sid={$this->sid}")); // 转入发起页
		} else {
			/* 支付转入 */
			if ( empty($payApitype) ) {
				$order = $this->getOrder ( $orderId );
				$this->assign ( "order", $order );
				$this->display ( "{$this->modelControllerName}/showOrder" );
			} else {
				redirect($this->getPayUrl(array(
					'id' => $orderId,
					'sid' => $this->cid,
					'apitype' => $payApitype,
				)));
			}
		}
		exit ();
	}
	
	/**
	 * 验证当前积分是否充足
	 * @param unknown $inputCurrency
	 */
	public function checkCurrency( $inputCurrency ) {
	    $scoreHandle = DistributionShopScore::getInstance("TradeReward", array('cid'=>$this->cid, 'uid' => $this->uid));
	    $userScore = $scoreHandle->getEnabledScore();
	    if ( $userScore >= $inputCurrency*1 ) {
	        return true;
	    }
	    return false;
	}
	
	/**
	 * 添加订单
	 */
	public function addOrder( $orderNo, $payApitype ) {
		$sessionOrder = session ( "order" ); // 要保存的订单
		$addressLists = $sessionOrder ['addressLists'];
		$shippingId = I("shipping_id", 0, "intval");
		
		/* 获得订单 */
		if ( !$sessionOrder || $sessionOrder ['orderNo'] !== $orderNo ) {
			$orderSaved = M("DistributionShopOrder")->where(array( 'order_id'=>$orderNo, 'cid'=>$this->cid) )->find();
			if ( $orderSaved ) { // 订单已存在时
				$this->error ( "订单($orderNo)已超时,正在转向订单详细重新结算.",  U('DisShopOrder/showOrder', "id={$orderSaved['id']}&sid={$this->cid}"));
			} elseif ( !$sessionOrder || $sessionOrder and (time () - $sessionOrder ["createTime"]) > 3 * 60 ) { // 下单超时
				$this->error ( "订单($orderNo){$sessionOrder ['orderNo']}已超时,正在转向购物车重新结算.",  $this->getCartUrl());
			}
		}
		
		/* 是否支持货到付款 */
		if( $payApitype == "COD" ) {
			if ( !$sessionOrder['supportCod'] ) {
				$this->error ( "当前订单不支持货到付款" );
			}
		}
		
		/* 获得收货地址 */
		$deliverAddress = $this->getAddress();
		$deliverAddress or $this->error ( "没有找到默认的收货地址" );
		
		/* 配送费 */
		if ( isset($sessionOrder['totalShippingArray']) ) {
		    $shippingTotalPrice = $sessionOrder['totalShippingArray'][$shippingId]*1;
		} else {
		    $shippingTotalPrice = $sessionOrder ['shippingTotalPrice']; // 配送信息
		}
		
		
		/* 购买时的代理商  */
		$aid = $this->getRealAid($deliverAddress);
		
		/* 保存订单 */
		$orderData = array (
				'order_id' => $orderNo,
				'cid' => $this->cart->getCid(),
				'uid' => $this->cart->getUid (),
				'agent_id' => $aid*1, // 支持代理模式
				'shipping_fee' => $shippingTotalPrice,
				'goods_amount' => $sessionOrder ['goodsTotalPrice'],
				'order_status' => DistributionShopOrderModel::ORDER_STATUS_PAY,
				'consignee' => $deliverAddress ['name'],
				'province' => $deliverAddress ['province'],
				'city' => $deliverAddress ['city'],
				'area' => $deliverAddress ['area'],
				'address' => $deliverAddress ['address'],
				'zipcode' => $deliverAddress ['zipcode'],
				'tel' => $deliverAddress ['tel'],
				'express_name' => '',
				'create_time' => $sessionOrder ['createTime'],
				'confirm_time' => 0,
				'shipping_time' => 0,
				'support_cod' => $sessionOrder['supportCod'],
    		    'reward_currency' => $sessionOrder['rewardCurrency'],
    		    'currency_value' => $sessionOrder['currencyValue'],
		);
		
		$redOffset = 0; // 抵消金额
		
		/* 使用的优惠卷 */
		$packetCode = I('packetCode', '');
		$orderData['red_packet_offset'] = 0;
		$packetCode and ( $redPacket = M("DistributionShopRedPacket")->where(array('uid'=>$this->uid, 'code'=>$packetCode, 'efficacy'=>1))->find() or $this->error ( "您选择了无效的优惠卷" ) );
		if ( $redPacket ) {
			$orderData['red_packet_offset'] = $redOffset = $redPacket['value'];
			$orderData['red_packet_id'] = $redPacket['id'];
		}
		
		/* 用户使用积分 */
		$tmpCurrencyOffset = 0; // 使用积分
		$tmpCurrencyRmb = 0; // 抵现
		if ( $sessionOrder['currencyValue'] ) { // 支持使用积分
		    $currencyOffset = I("currency_offset", 0, "intval");
		    ($currencyOffset > $sessionOrder['currencyValue']) and $this->error("输入的积分不得大于{$sessionOrder['currencyValue']}");
		    if ( $currencyOffset ) {
		        $success = $this->checkCurrency($currencyOffset) or $this->error("可用积分不足");
		    }
		    $tmpCurrencyOffset = $currencyOffset*1;
		    $tmpCurrencyRmb = sprintf("%.2f", $tmpCurrencyOffset*$this->config['currency_config']['value']/100); 
		}
		
		/* 计算实际返积分 */
		$tmpActualRewardCurrency = 0;
		if ( $sessionOrder['rewardCurrency'] ) {
		    if ( $tmpCurrencyOffset*1 ) {
		       $actualRewardCurrency = $sessionOrder['rewardCurrency'] - ceil($tmpCurrencyOffset/10)*1; // 每用10积分少返1积分
		       $tmpActualRewardCurrency = $actualRewardCurrency = $actualRewardCurrency > 0 ? $actualRewardCurrency : 0;
		    } else {
		       $tmpActualRewardCurrency = $sessionOrder['rewardCurrency'];
		    }
		}
		
		/* 临时数据支付成功后成立 */
		$orderData['currency_tmp'] = serialize(array(
		    'currency_offset' => $tmpCurrencyOffset,
		    'currency_rmb' => $tmpCurrencyRmb,
		    'actual_reward_currency' => $tmpActualRewardCurrency,
		));
		
		/* 实际消费总额 */
		$orderData['actual_cost'] = $shippingTotalPrice + $sessionOrder ['goodsTotalPrice'] - $redOffset - $tmpCurrencyRmb ;
		
		/* 订单添加前 */
		method_exists($this, "_before_add_order") and $this->_before_add_order( $orderData );
		
		$d = D ( "DistributionShopOrder" );
		if ( $orderId = $d->add ( $orderData ) ) {
		    session ( "order", null );
			$orderData['id'] = $orderId;
			// 添加所有订单商品
			$m = M ( "DistributionShopOrderGoods" );
			$goodsList = $this->getOrderGoods( $sessionOrder['orderItems'], $orderId);
			if ( false != $m->addAll ( $goodsList ) ) {
				$sessionOrder ['atOnce'] or $this->cart->clearAll ();
				/*订单创建后操作*/
				method_exists($this, "_after_add_order") and $this->_after_add_order( $orderData );
				/*更新订单总佣金*/
				$baseRewards = DistributionShopOrderModel::calcRewardBonus($goodsList);
				$dealerRewards = DistributionShopOrderModel::calcRewardBonusDealer($goodsList);
				$baseBonus = array_sum(array_values($baseRewards['totalUser']));
				$dealerBonus = array_sum(array_values($dealerRewards['totalUser']));
				$modifyData = array(
						'total_bonus' => $baseRewards['orderBonus'] + $dealerRewards['orderBonus'], // 非实际佣金
						'reward_uids' => join(',', array_keys($baseRewards['totalUser'])),
						'reward_bonus' => join(',', array_values($baseRewards['totalUser'])),
						'reward_uids_dealer' => join(',', array_keys($dealerRewards['totalUser'])),
						'reward_bonus_dealer' => join(',', array_values($dealerRewards['totalUser'])),
						'surplus' => $sessionOrder ['goodsTotalPrice'] - ($baseBonus + $dealerBonus), // 盈余 = 订单总额 - 基础用户实际发放的佣金总和 + 金牌会员实际发放的佣金总和）
				);
				$orderData = array_merge( $orderData, $modifyData );
				/* 绑定订单代理分成 */
				$modifyAgentReward = $this->bindOrderAgentReward( $orderData );
				$modifyAgentReward and $modifyData = array_merge($modifyData, $modifyAgentReward);
				$d->where('id=%d', $orderId)->save($modifyData);
				return $orderId;
			} else {
			    SystemInfo::log("save_order_goods", array(
    			    'goodsList' => $goodsList,
    			    'sql' => M()->getLastSql()
			    ));
				$d->where ( "id=%d", $orderId )->setField ( "order_status", DistributionShopOrderModel::ORDER_STATUS_INVALID );
			}
		}
		$this->error ( '订单保存错误.' );
	}
	
	/**
	 * 绑定订单代理分成信息
	 */
	public function bindOrderAgentReward( &$orderData = array() ) {
	    $modifyData = array();
	    $aid = $orderData['agent_id'];
	    $orderSurplus = $orderData['surplus'];
	    $agentShopConfig = $this->config["agent_shop_config"];
	    if ( $agentShopConfig ) { // 代理商城配置存在
	        $agentNotStock = $agentShopConfig["agentNotStock"]; // 代理商是否开启分佣
	        if ( $agentNotStock ) {
	            if ( $agentShopConfig['rewardMode'] == 0 ) { // 按层级关系树多级分佣
	                $modeConfig = $agentShopConfig['modeConfig'][0];
	                if ( $modeConfig['agent_reward_percent'] ) {
	                    if ( !$this->agentLayerTree ) {
	                        // 获得层级树
	                        $seller = $agent = M("Agent")->where("id=%d", $aid )->find(); // 代理商
	                        if ( $seller ) {
	                            $curlevel = $seller['level']*1; // 代理商等级
	                            $agentLayerTree = $seller['id']; // 层级树
	                            while ( $agent['parent_id']*1 != 0 ) {
	                                $agent = M("Agent")->where("id=%d", $agent['parent_id'] )->find(); // 上级代理商
	                                $spaceLevel = $curlevel - $agent['level'] - 1;
	                                for ( $i=0; $i<$spaceLevel; $i++ ) {
	                                    $agentLayerTree.=",0";
	                                }
	                                $agentLayerTree.= ",{$agent['id']}";
	                                $curlevel = $agent['level'];
	                            }
	                            if ( $curlevel ) {
	                                $spaceLevel = $curlevel;
	                                for ( $i=0; $i<$spaceLevel; $i++ ) {
	                                    $agentLayerTree.=",0";
	                                }
	                            }
	                            $this->agentLayerTree = $agentLayerTree.",s";
	                        } else {
	                            $this->agentLayerTree = "s";
	                        }
	                    }
	                    $altArray = array_reverse(explode(",", $this->agentLayerTree)); // 分佣树 s,0,....
	                    $percentArray =  explode(":", $modeConfig['agent_reward_percent']); // 分佣比例 s,0,....
	                    /* 补齐与裁剪 */
	                    if ( count($altArray) < count($percentArray) ) {
	                        $altArray = array_pad($altArray, count($percentArray), 0); // 补齐代理
	                    } elseif ( count($altArray) > count($percentArray) ) {
	                        $altArray = array_slice($altArray, 0, count($percentArray)); // 裁剪代理层级树
	                    }
	                    /* 合并比例(无用户并入邻近上级) */
	                    for( $i=count($altArray)-1; $i>0; $i--) {
	                        if ( $altArray[$i] == 0 and isset($altArray[$i-1]) ) {
	                            $percentArray[$i-1] += $percentArray[$i];
	                            $percentArray[$i] = 0;
	                        }
	                    }
	                    /* 盈余再次给厂家与代理分成 */
	                    $rewardBonusAgent = array();
	                    foreach ( $percentArray as $v ) {
	                        $rewardBonusAgent[] = $orderSurplus*($v/100);
	                    }
	                    $modifyData['reward_aids'] = $orderData['reward_aids_agent'] = join(",", $altArray);
	                    //$modifyData['reward_percent_agent'] = $orderData['reward_percent_agent'] = join(":", $percentArray);
	                    $modifyData['reward_bonus_agent'] = $orderData['reward_bonus_agent'] = join(",", $rewardBonusAgent);
	                }
	            } elseif ( $agentShopConfig['rewardMode'] == 1 ) { // 按推荐关系树二级分佣(区分代理等级)
	                $modeConfig = $agentShopConfig['modeConfig'][1];
	                if ( !empty($modeConfig['agent_reward_percent']) ) {
	                    $agentRewardPercentConfig = $modeConfig['agent_reward_percent']; // 分佣比例配置
	                    /* 获得推荐树 */
	                    $agent = M("Agent")->where("id=%d", $aid )->find(); // 代理商
	                    $agentTree = $agent['tree']; // 代理推荐树
	                    $agentTree = explode(',', $agentTree);
	                    /* 分佣树 */
	                    $altArray = array_slice($agentTree, -2, 2);
	                    if ( $altArray ) {
	                        $agentList = M("Agent")->where(array('id'=>array('in', $altArray)))->getField("id,level");
	                        $altLevel = array(); // 分佣代理等级
	                        $agentRewardPercent = $agentRewardPercentConfig;
	                        for ( $i = count($altArray)-1; $i >= 0; $i-- ) {
	                            $agentId = $altArray[$i];
	                            if ( isset($agentList[$agentId]) ) { // 代理存在
	                                $level = $altLevel[] = $agentList[$agentId];
	                            } else { // 代理不存在
	                                $altArray[$i] = 0; // 代理用户id改0
	                                $level = $altLevel[] = -1;
	                            }
	                            $agentRewardPercent = $agentRewardPercent[$level];
	                        }
	                        if ( is_array($agentRewardPercent) ) { // 根极代理直接卖出
	                            $agentRewardPercent = $agentRewardPercent["-1"];
	                        }
	                        if ( is_string($agentRewardPercent) ) {
	                            $percentArray = array_reverse(explode(":", $agentRewardPercent));
	                            $agentRewardPercentArray = array_combine($altArray, $percentArray);
	                            if ( $agentRewardPercentArray ) { // 计算比例成功
	                                /* 盈余再次给代理分成 */
	                                $rewardBonusAgent = array();
	                                foreach ( $percentArray as $v ) {
	                                    $rewardBonusAgent[] = $orderSurplus*($v/100);
	                                }
	                                $modifyData['reward_aids'] = $orderData['reward_aids_agent'] = join(",", $altArray);
	                                //$modifyData['reward_percent_agent'] = $orderData['reward_percent_agent'] = join(":", $percentArray);
	                                $modifyData['reward_bonus_agent'] = $orderData['reward_bonus_agent'] = join(",", $rewardBonusAgent);
	                                
	                            }
	                        }
	                    }
	                }
	            } elseif ( $agentShopConfig['rewardMode'] == 2 ) { // 按推荐关系树多级分佣(区分代理等级)
	                $modeConfig = $agentShopConfig['modeConfig'][2];
	                if ( !empty($modeConfig['agent_reward_percent']) ) {
	                    $agentRewardPercentConfig = $modeConfig['agent_reward_percent']; // 分佣比例配置
	                    /* 获得推荐树 */
	                    $agent = M("Agent")->where("id=%d", $aid )->find(); // 代理商
	                    $agentTree = $agent['tree']; // 代理推荐树
	                    $agentTree = explode(',', $agentTree);
	                    /* 分佣树 */
	                    $altArray = array_slice($agentTree, 0, 3);
	                    if ( $altArray ) {
	                        $agentList = M("Agent")->where(array('id'=>array('in', $altArray)))->getField("id,level");
	                        $altLevel = array(); // 分佣代理等级
	                        $agentRewardPercent = $agentRewardPercentConfig;
	                        for ( $i = count($altArray)-1; $i >= 0; $i-- ) {
	                            $agentId = $altArray[$i];
	                            if ( isset($agentList[$agentId]) ) { // 代理存在
	                                $altLevel[] = $agentList[$agentId];
	                            } else { // 代理不存在
	                                $altArray[$i] = 0; // 代理用户id改0
	                                $altLevel[] = -1;
	                            }
	                        }
	                        $levelPath = join('.', $altLevel);
	                        if ( isset($agentRewardPercentConfig[$levelPath]) ) {
	                            $agentRewardPercent = $agentRewardPercentConfig[$levelPath];
	                            if ( is_string($agentRewardPercent) ) {
	                                $percentArray = array_reverse(explode(":", $agentRewardPercent));
	                                $agentRewardPercentArray = array_combine($altArray, $percentArray);
	                                if ( $agentRewardPercentArray ) { // 计算比例成功
	                                    /* 盈余再次给代理分成 */
	                                    $rewardBonusAgent = array();
	                                    foreach ( $percentArray as $v ) {
	                                        $rewardBonusAgent[] = $orderSurplus*($v/100);
	                                    }
	                                    $modifyData['reward_aids'] = $orderData['reward_aids_agent'] = join(",", $altArray);
	                                    //$modifyData['reward_percent_agent'] = $orderData['reward_percent_agent'] = join(":", $percentArray);
	                                    $modifyData['reward_bonus_agent'] = $orderData['reward_bonus_agent'] = join(",", $rewardBonusAgent);
	                                }
	                            }
	                        }
	                    }
	                }
	            }
	        }
	    }
	    return $modifyData;
	}
	
	/**
	 * 确认收货
	 */
	public function signInAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "DistributionShopOrder" );
		DBRW::openAndClose(0);
		$order = $d->find( $orderId );
		DBRW::openAndClose(1);
		if($order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN) {
			// 更新订单状态
			$data = array("order_status" => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
						"take_time" => time(),
						"deal_time" => time(),);
			if( false !== $d->where ( array ( "uid" => $this->uid, "id" => $orderId, ) )
							->save ( $data ) ) {
					$order = array_merge($order, $data);
					$this->afterOrderCompleted( $order );
					$this->ajaxSuccess ( "交易成功" );
			}
		} else {
			$this->ajaxError ( "非已发货状态，不能完成收货操作。" );
		}
		$this->ajaxError ( "提交失败，请重新确认收货" );
	}
	
	
	/**
	 * 获得要结算的商品
	 * 立即购买:
	 * $_GET = array(
	 * 	  'id' => 0,
	 * 	  'quantity' => 1,
	 * 	  'attrs' => array(
	 * 		  '属性1' => '属性值1'
	 * 	   ),
	 * )
	 * @return array
	 * array(
	 * 	  "atOnce" => 0, // 是否立即购买
	 * 	  "items" => array (
	 * 			array(
	 * 				$businessId => array(
	 * 					'businessId' => $businessId,
	 * 					'productPrice' => 0.00,
	 * 					'quantity' => $quantity,
	 * 					'attrs' => array(
	 * 						'属性名1' => '属性值1',
	 * 					),
	 * 					'pic' => '',
	 * 				)
	 * 			),
	 * 			... ...
	 * 	  ),
	 * )
	 */
	protected function getItems() {
		$items = array (
				"atOnce" => 0, // 是否立即购买
				"items" => array ()
		);
		$goodsId = I ( "id", 0, "intval" ); // 商品id(立即购买时)
		if ( !$goodsId ) { // 处理从购物车中选择的商品
			$items ["items"] = $this->cart->getItems (); // 暂时购买所有商品
			$d = D ( "My/DistributionShopGoods", "Model" );
			foreach ( $items ["items"] as $productId => &$product ) {
			    foreach ( $product["items"] as $businessId => &$attrProduct ) {
			        $goods = $d->getUserSubmitGoods ( $productId, $attrProduct['attr'] );
			        if ( !$goods ) {
			            if ( IS_AJAX )
			                $this->ajaxError ( $d->getError () );
			            else
			                $this->error ( $d->getError () );
			        }
			        /* 临时积分数据  */
			        $attrProduct['rewardCurrency'] = $goods['rewardCurrency'];
			        $attrProduct['currencyValue'] = $goods['currencyValue'];
			    }
			}
		} elseif( $goodsId ) { // 处理立即购买的商品
			$id = I ( "id", 0, "intval" );
			$quantity = I ( "quantity", 1, "intval" ) and $quantity === 0 and $quantity = 1;
			$attrs = I ( "attrs", null );
			$d = D ( "My/DistributionShopGoods", "Model" );
			// 处理立即购买属性参数,如果提交类型为数组则转为字符串类型(购买链接会再次使用)
			$goods = $d->getUserSubmitGoods ( $id, $attrs );
			if ( !$goods ) {
				if ( IS_AJAX )
					$this->ajaxError ( $d->getError () );
				else
					$this->error ( $d->getError () );
			}
			// 转化为CartItem(参考购物车结构)
			$businessId = $this->cart->getBusinessId ( $goods ['id'] );
			$items ["atOnce"] = 1;
			$items ["items"] [$goods ['id']] = array (
					'productId' => $goods ['id'],
					'name' => $goods ['name'],
					'support_cod' => $goods ['support_cod'],
					'items' => array (
							$businessId => array (
								'businessId' => $businessId,
								'productPrice' => $goods ['productPrice'],
								'quantity' => $quantity,
								'attrs' => $goods ['selectedAttributes'],
								'pic' => $goods['images'][0] ? $goods['images'][0] : '',
							    'rewardCurrency'=> $goods['rewardCurrency'],
							    'currencyValue'=> $goods['currencyValue'],
							    'goodsSnap' => $goods,
							)
					)
			);
		}
		return $items;
	}
	
	/**
	 * 获得可持久化的订单商品数据
	 * @param unknown $orderItems
	 * @param unknown $orderId
	 * @return multitype:multitype:unknown NULL
	 */
	protected function getOrderGoods( $orderItems, $orderId, $wparam = array() ) {
		$goodsList = array();
		foreach ( $orderItems as $v ) {
			/* 创建可保存的订单商品格式 */
			foreach ( $v ["items"] as $v0 ) {
			    /* 分成商品 */
			    $shopGoodsSnap = $v0['goodsSnap'];
				/* 分成信息 */
				$res = $this->getPercentAndUsers($shopGoodsSnap, $v0);
				$base = $res['base'];
				$uids = $base[0];
				$rewardPercent = $base[1];
				$rewardPrice = $base[2];
					
				$dealer = $res['dealer'];
				$franchisedDealerUids = $dealer[0];
				$rewardPercentDealer = $dealer[1];
				$rewardPriceDealer = $dealer[2];
				
				$rewardBonus = DistributionShopOrderModel::calcSimpleRewardBonus($uids, $rewardPercent, $v0['quantity']*$rewardPrice);
				$rewardBonusDealer = DistributionShopOrderModel::calcSimpleRewardBonus($franchisedDealerUids, $rewardPercentDealer, $v0['quantity']*$rewardPriceDealer);

				$orderGoodsItem = array (
						'order_id' => $orderId,
						'product_id' => $v ['productId'],
						'product_name' => $v ['name'],
						'product_pic' => $v0 ['pic'],
						'product_number' => $v0 ['quantity'],
						'product_price' => $v0 ['productPrice'],
						'product_attr' => arrayToString ( $v0 ['attrs'] ),
						/* 基础 */
						'reward_price' => $rewardPrice, // 佣金/件
						'reward_uids' => join(',', $uids), // 返佣金用户
						'reward_percent' => join(':', $rewardPercent), // 佣金比例
						'reward_bonus' => join(',', $rewardBonus),
						/* 特约经销商 */
						'reward_price_dealer' => $rewardPriceDealer, // 特约经销商佣金/件
						'reward_uids_dealer' => join(',', $franchisedDealerUids), // 返佣金特约经销商用户
						'reward_percent_dealer' => join(':', $rewardPercentDealer), // 佣金比例
						'reward_bonus_dealer' => join(',', $rewardBonusDealer),
				        'goods_snap' => serialize($shopGoodsSnap),
				);
				/* 代理商分佣 */
				$goodsSurplus = $orderGoodsItem['product_price']*$orderGoodsItem['product_number'] - (array_sum($rewardBonus) + array_sum($rewardBonusDealer)); // 当前商品的盈余 = 商品拍下单价 * 商品数量 - (金牌会员实发佣金 + 普通会员实发佣金)
				$orderGoodsItem['reward_total_agent'] = $goodsSurplus;
				$goodsList [] = $orderGoodsItem;
			}
				
		}
		return $goodsList;
	}
	
	/**
	 * 获得订单中一个产品的分成比例与分成用户
	 * @param array $shopGoods 所买商品
	 * @param array $orderGoodsItem 订单商品（支付前的订单商品格式,即getItems的格式）
	 * @return multitype:multitype:multitype: unknown
	 */
	protected function getPercentAndUsers( $shopGoods, $orderGoodsItem ) {
		
		/* 基础佣金 */
		$rewardPrice = $shopGoods['reward_price']; // 基础佣金
		
		/* 特约经销商佣金 */
		$rewardPriceDealer = $shopGoods['reward_price_dealer']; // 金牌会员佣金
		
		/* 特约经销购买时 */
		$userRole = new UserRole();
		if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) { // 金牌会员 
		    if ( ($shopGoods['dealer_price'] and (($shopGoods['dealer_price'] - $orderGoodsItem['productPrice']) == 0)) // 以金牌会员价购买的佣金(当前金牌会员价-拍下价格=0)
					or 
				  isset($this->config['discount_open']) and $this->config['discount_open'] // 金牌会员折扣价购买
			) {
		        $rewardPrice = $shopGoods['reward_price2']; // 金牌会员价下基础佣金
		        $rewardPriceDealer = $shopGoods['reward_price2_dealer'];  // 金牌会员价下金牌会员佣金
		    }
		}
		
		/* 基础分成发放比例 */
		$rewardPercent = array();
		if ( $shopGoods['reward_set'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent'] and $rewardPercent = explode(':', $shopGoods['reward_percent']);
		} else { // 系统默认分成比例
			$this->config['reward_percent'] and $rewardPercent = explode(':', $this->config['reward_percent']);
		}
		
		/* 获得参与佣金发放的用户  */
		$tree = M("DistributionShopUserTree")->where(array('cid'=>$this->cid, 'uid'=>$this->uid))->getField("tree");
		$uids = explode(',', $tree);
		array_shift($uids);
		
		/* 特约经销商分成发放比例  */
		$rewardPercentDealer = array();
		if ( $shopGoods['reward_set_dealer'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $shopGoods['reward_percent_dealer']);
		} else { // 系统默认分成比例
			$this->config['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $this->config['reward_percent_dealer']);
		}
		
		/** 用户筛选出特约与基础用户(固位模式筛选) */
		$userRole = new UserRole();
		$baseUids = array(); // 基础用户
		$franchisedDealerUids = array(); // 特约经销商
		$userInfo = array();
		if ( $uids ) {
			$userInfo = M("WechatUser")->where(array('id'=>array('in', $uids)))->order("find_in_set(id, '{$tree}')")->getField("id,type");
			for ( $i=0; $i < count($uids); $i++ ) {
				/* 初始值设定位置分成用户0 */
				$baseUids[$i] = 0;
				$franchisedDealerUids[$i] = 0;
				if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 代理用户
					// 代理商
				}
				if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) { // 筛选特约经销商用户 (从非代理用户)
					$franchisedDealerUids[$i] = $uids[$i];
				}
				if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_STANDARD) ) { // 普通会员
					$baseUids[$i] = $uids[$i];
				}
			}
		}
		
		/* 基础用户分成与分成比例 */
		$baseUids = array_slice($baseUids, 0, count($rewardPercent)); // 分配比例 -> 裁剪分销用户
		$rewardPercent = array_slice($rewardPercent, 0, count($baseUids));  // 分销用户 -> 裁剪分配比例
		$uidCount = count($baseUids);
		for( $i = 0; $i < $uidCount; $i++ ) { // 清除uid为0的用户
			if ( !$baseUids[$i]*1 ) {
				unset($baseUids[$i]);
				unset($rewardPercent[$i]);
			}
		}
		
		/* 金牌会员分成与分成比例 */
		$franchisedDealerUids = array_slice($franchisedDealerUids, 0, count($rewardPercentDealer)); // 分配比例 -> 裁剪分销用户
		$rewardPercentDealer = array_slice($rewardPercentDealer, 0, count($franchisedDealerUids));  // 分销用户 -> 裁剪分配比例
		$uidCount = count($franchisedDealerUids);
		for( $i = 0; $i < $uidCount; $i++ ) { // 清除uid为0的用户
			if ( !$franchisedDealerUids[$i]*1 ) {
				unset($franchisedDealerUids[$i]);
				unset($rewardPercentDealer[$i]);
			}
		}
		
		return array(
			'base' => array($baseUids, $rewardPercent, $rewardPrice),
			'dealer' => array($franchisedDealerUids, $rewardPercentDealer, $rewardPriceDealer),
		);
	}
	
	
	/**
	 * 交易成功后
	 * @param int $orderId
	 */
	protected function afterOrderCompleted( $order ) {
		$eventData = array('order' => $order);
		tag('disorder_completed', $eventData);
	}
	
	/**
	 * 订单详细
	 */
	public function showOrderAction() {
		$id = I ( "id", 0, "intval" );
		$order = $this->getOrder ( $id );
		/* 待支付订单跳转入重新进入确认页 */
		if ( in_array('pay', $order['operates'] ) ) { // 支付
			$controller = "DisShopOrder";
			if ( $order['buy_method'] == DistributionShopOrderModel::BUY_METHOD_GIFTS ) {
				$controller = 'DisShopGiftsOrder';
			} elseif ( $order['buy_method'] == DistributionShopOrderModel::BUY_METHOD_TRY ) {
				$controller = 'DisShopTryOrder';
			}
			redirect(U("{$controller}/confirmOrder", array('sid'=>$this->cid, 'orderId'=>$id)));
		} elseif ( in_array('payAnother', $order['operates'] ) ) { // 发起代付
			/* 代支付订单跳转  */
			if ( $order['buy_method'] == DistributionShopOrderModel::BUY_METHOD_COQUETRY ) {
				$controller = "DisShopCoquetryOrder";
				redirect(U("{$controller}/confirmOrder", array('sid'=>$this->cid, 'orderId'=>$id)));
			}
		}
		/* 捐赠 */
		if ( $this->config['donate_on'] ) {
		    $distributionShopLogic = D("Home/DistributionShop", "Logic");
		    $donateTotal = $distributionShopLogic->getDonateTotal($order);
		    if ( $donateTotal ) {
		        $projectLists = DistributionShopDonate::getDonateProjectLists($this->cid);
		        foreach ( $projectLists as $k => $v) {
		            $projectOptions[$v['id']] = $v['name'];
		        }
		        $projectOptions and $this->assign ( "projectOptions", $this->getOption($projectOptions) );
		    }
		}
		$this->assign ( "order", $order );
		$this->display ( "{$this->modelControllerName}/showOrder" );
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrderAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "DistributionShopOrder" );
		$d->where ( array (
				"uid" => $this->uid,
				"id" => $orderId
		) )->setField ( "order_status", DistributionShopOrderModel::ORDER_STATUS_CANCELED ) and $this->ajaxSuccess ( "取消成功" );
		$this->ajaxError ( "取消失败" );
	}
	
	/**
	 * 获得用户收货地址
	 * @param $auto 自动寻找默认
	 * @return array
	 */
	protected function getAddress( $addressId = 0, $auto = 1 ) {
		$condition = array(
			'address.uid' => $this->uid,
			'address.status' => 1,
		);
		if ( $addressId ) {
			$condition['address.id'] = $addressId;
			unset($condition['address.status']);
		} elseif ( !$auto ) {
			return null;
		}
		$address = M ( "DistributionShopDeliverAddress address" )->join ( "__CN_PROVINCE__ province on address.province = province.code", "LEFT" )
										->join ( "__CN_CITY__ city on address.city = city.code", "LEFT" )
										->join ( "__CN_AREA__ area on address.area = area.code", "LEFT" )
										->field ( "address.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
										->where ( $condition )
										->order ( "address.status desc" )
										->find ();
		return $address;
	}
	
	
	/**
	 * 绑定订单详细
	 * @param unknown $orderLists 查询出的订单列表
	 */
	protected function bindOrderDetail(&$orderLists) {
		D( "My/DistributionShopOrder" )->bindOrderDetail($orderLists);
	}
	
	/**
	 * 获得订单操作
	 * @param array $order 已获得详细信息的订单
	 * @return string
	 */
	protected function getOrderOperate( $order ) {
		return D( "My/DistributionShopOrder" )->getOrderOperate( $order );
	}
	
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return array
	 */
	protected function getOrder($id) {
		return D( "My/DistributionShopOrder" )->getOrder($id);
	}
	
	/**
	 * 购物车页
	 */
	protected function getCartUrl() {
		return url ( null, 'DisShopCart', 'showCart', "sid={$this->sid}" );
	}
	
	/**
	 * 获得购物车
	 */
	protected function getCart() {
		return \Utuo\DisCart::getCart ($this->uid, $this->sid ); 
	}
	
	/**
	 * 支付方式列表
	 * @return multitype:
	 */
	protected function getPayApiList() {
		$m = M("ProductPayApi");
		$produtPayApiLists = $m->where("cid=%d and status=1", $this->sid)->getField("tag,name") or $produtPayApiLists = array(); // 获得商家设置的支付接口
		return $produtPayApiLists;
	}
	
	/**
	 * 获得支付链接
	 * array(
	 * 	'id' => '', // 订单id
	 * 	'sid' => '', // 客户id
	 * 	'apitype' => '', // 支付方式
	 * )
	 */
	protected function getPayUrl($params) {
		$url = __APP__."/".MODULE_NAME."/DisShopPay/toPay?id={$params['id']}&sid={$params['sid']}&apitype={$params['apitype']}";
		return $url;
	}
	
	/**
	 * 添加订单之前的处理函数
	 * @param unknown $orderData
	 */
	protected function _before_add_order( &$orderData ) {}
	
	
	/**
	 * 添加订单之后的处理函数
	 * @param unknown $orderData
	 */
	protected function _after_add_order( &$orderData ) {}
	
	/**
	 * 获得欲下订单数据后
	 * @param unknown $savingOrderData
	 */
	protected function _after_get_saving_order( &$savingOrderData ) {}
}